<template>
  <div class="service-management">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h1>服务项目管理</h1>
        <p class="description">管理洗护服务项目，设置价格和服务流程</p>
      </div>
      <div class="header-right">
        <el-button type="success" @click="showAddDialog">
          <el-icon><Plus /></el-icon>
          添加服务
        </el-button>
        <el-button type="primary" @click="refreshData">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 服务统计 -->
    <div class="service-stats">
      <div class="stat-card">
        <div class="stat-icon active">
          <el-icon><Shop /></el-icon>
        </div>
        <div class="stat-content">
          <h3>{{ serviceStats.active || 0 }}</h3>
          <p>启用服务</p>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon popular">
          <el-icon><Star /></el-icon>
        </div>
        <div class="stat-content">
          <h3>{{ serviceStats.popular || 0 }}</h3>
          <p>热门服务</p>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon revenue">
          <el-icon><Money /></el-icon>
        </div>
        <div class="stat-content">
          <h3>¥{{ serviceStats.totalRevenue || '0.00' }}</h3>
          <p>总收入</p>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon orders">
          <el-icon><Document /></el-icon>
        </div>
        <div class="stat-content">
          <h3>{{ serviceStats.totalOrders || 0 }}</h3>
          <p>总订单数</p>
        </div>
      </div>
    </div>

    <!-- 筛选区域 -->
    <div class="filter-section">
      <el-form :model="filterForm" inline>
        <el-form-item label="服务名称">
          <el-input
            v-model="filterForm.name"
            placeholder="请输入服务名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="服务类型">
          <el-select
            v-model="filterForm.type"
            placeholder="请选择类型"
            clearable
            style="width: 150px"
          >
            <el-option
              v-for="(label, value) in LAUNDRY_SERVICE_TYPE"
              :key="value"
              :label="label"
              :value="value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="服务状态">
          <el-select
            v-model="filterForm.status"
            placeholder="请选择状态"
            clearable
            style="width: 120px"
          >
            <el-option label="启用" value="active" />
            <el-option label="禁用" value="inactive" />
          </el-select>
        </el-form-item>
        <el-form-item label="价格范围">
          <el-input-number
            v-model="filterForm.minPrice"
            placeholder="最低价"
            :min="0"
            style="width: 100px"
          />
          <span style="margin: 0 8px">-</span>
          <el-input-number
            v-model="filterForm.maxPrice"
            placeholder="最高价"
            :min="0"
            style="width: 100px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 服务列表 -->
    <div class="service-list">
      <el-table
        v-loading="loading"
        :data="serviceList"
        stripe
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="服务图片" width="80">
          <template #default="{ row }">
            <el-image
              :src="row.image || '/default-service.png'"
              :preview-src-list="[row.image]"
              fit="cover"
              style="width: 50px; height: 50px; border-radius: 6px"
            />
          </template>
        </el-table-column>
        <el-table-column prop="name" label="服务名称" width="160" />
        <el-table-column label="服务类型" width="120">
          <template #default="{ row }">
            <el-tag size="small" effect="plain">
              {{ LAUNDRY_SERVICE_TYPE[row.type] }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="服务描述" min-width="200" show-overflow-tooltip />
        <el-table-column label="价格信息" width="120">
          <template #default="{ row }">
            <div class="price-info">
              <div class="price">¥{{ row.price }}</div>
              <div class="unit">{{ row.unit }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="处理时间" width="100">
          <template #default="{ row }">
            <span>{{ row.processingTime }}小时</span>
          </template>
        </el-table-column>
        <el-table-column label="服务状态" width="100">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              active-value="active"
              inactive-value="inactive"
              @change="handleStatusChange(row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="销量" width="80">
          <template #default="{ row }">
            <span class="sales-count">{{ row.salesCount || 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="评分" width="100">
          <template #default="{ row }">
            <el-rate
              v-model="row.rating"
              disabled
              show-score
              text-color="#ff9900"
              score-template="{value}"
              size="small"
            />
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="更新时间" width="140">
          <template #default="{ row }">
            {{ formatDateTime(row.updateTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button
                type="primary"
                link
                size="small"
                @click="viewServiceDetail(row)"
              >
                查看详情
              </el-button>
              <el-button
                type="warning"
                link
                size="small"
                @click="editService(row)"
              >
                编辑
              </el-button>
              <el-button
                type="info"
                link
                size="small"
                @click="managePricing(row)"
              >
                价格管理
              </el-button>
              <el-dropdown @command="(command) => handleServiceAction(row, command)">
                <el-button type="primary" link size="small">
                  更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="copy">复制服务</el-dropdown-item>
                    <el-dropdown-item command="stats">服务统计</el-dropdown-item>
                    <el-dropdown-item command="reviews">客户评价</el-dropdown-item>
                    <el-dropdown-item command="delete" divided>删除服务</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 批量操作 -->
    <div v-if="selectedServices.length > 0" class="batch-actions">
      <el-card>
        <div class="batch-content">
          <span>已选择 {{ selectedServices.length }} 项服务</span>
          <div class="batch-buttons">
            <el-button type="success" @click="batchUpdateStatus('active')">
              批量启用
            </el-button>
            <el-button type="warning" @click="batchUpdateStatus('inactive')">
              批量禁用
            </el-button>
            <el-button type="danger" @click="batchDelete">
              批量删除
            </el-button>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 服务表单弹窗 -->
    <ServiceFormDialog
      v-model:visible="formDialogVisible"
      :service="selectedService"
      @success="handleFormSuccess"
    />

    <!-- 服务详情弹窗 -->
    <ServiceDetailDialog
      v-model:visible="detailDialogVisible"
      :service="selectedService"
    />

    <!-- 价格管理弹窗 -->
    <PricingManagementDialog
      v-model:visible="pricingDialogVisible"
      :service="selectedService"
      @success="refreshData"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Refresh,
  Search,
  Shop,
  Star,
  Money,
  Document,
  ArrowDown
} from '@element-plus/icons-vue'
import {
  getLaundryServices,
  createLaundryService,
  updateLaundryService,
  deleteLaundryService,
  batchUpdateServiceStatus,
  LAUNDRY_SERVICE_TYPE
} from '@/api/laundry'
import ServiceFormDialog from './components/ServiceFormDialog.vue'
import ServiceDetailDialog from './components/ServiceDetailDialog.vue'
import PricingManagementDialog from './components/PricingManagementDialog.vue'

// 响应式数据
const loading = ref(false)
const serviceList = ref([])
const selectedServices = ref([])
const selectedService = ref(null)
const formDialogVisible = ref(false)
const detailDialogVisible = ref(false)
const pricingDialogVisible = ref(false)

// 筛选表单
const filterForm = reactive({
  name: '',
  type: '',
  status: '',
  minPrice: null,
  maxPrice: null
})

// 分页数据
const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

// 服务统计数据
const serviceStats = ref({
  active: 0,
  popular: 0,
  totalRevenue: '0.00',
  totalOrders: 0
})

// 方法
const formatDateTime = (date) => {
  return new Date(date).toLocaleString()
}

const loadServices = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      size: pagination.size,
      name: filterForm.name,
      type: filterForm.type,
      status: filterForm.status,
      minPrice: filterForm.minPrice,
      maxPrice: filterForm.maxPrice
    }

    const response = await getLaundryServices(params)
    serviceList.value = response.data.records || []
    pagination.total = response.data.total || 0

    // 计算统计数据
    const stats = {
      active: serviceList.value.filter(s => s.status === 'active').length,
      popular: serviceList.value.filter(s => s.salesCount > 100).length,
      totalRevenue: serviceList.value.reduce((sum, s) => sum + (s.totalRevenue || 0), 0).toFixed(2),
      totalOrders: serviceList.value.reduce((sum, s) => sum + (s.salesCount || 0), 0)
    }
    serviceStats.value = stats
  } catch (error) {
    ElMessage.error('获取服务列表失败')
    console.error('Load services error:', error)
  } finally {
    loading.value = false
  }
}

const refreshData = () => {
  loadServices()
}

const handleSearch = () => {
  pagination.page = 1
  loadServices()
}

const handleReset = () => {
  Object.assign(filterForm, {
    name: '',
    type: '',
    status: '',
    minPrice: null,
    maxPrice: null
  })
  pagination.page = 1
  loadServices()
}

const handleSelectionChange = (selection) => {
  selectedServices.value = selection
}

const handleSizeChange = (val) => {
  pagination.size = val
  pagination.page = 1
  loadServices()
}

const handleCurrentChange = (val) => {
  pagination.page = val
  loadServices()
}

const showAddDialog = () => {
  selectedService.value = null
  formDialogVisible.value = true
}

const viewServiceDetail = (service) => {
  selectedService.value = service
  detailDialogVisible.value = true
}

const editService = (service) => {
  selectedService.value = service
  formDialogVisible.value = true
}

const managePricing = (service) => {
  selectedService.value = service
  pricingDialogVisible.value = true
}

const handleStatusChange = async (service) => {
  try {
    await updateLaundryService(service.id, { status: service.status })
    ElMessage.success('状态更新成功')
    refreshData()
  } catch (error) {
    ElMessage.error('状态更新失败')
    // 回滚状态
    service.status = service.status === 'active' ? 'inactive' : 'active'
    console.error('Update status error:', error)
  }
}

const handleServiceAction = async (service, action) => {
  selectedService.value = service

  switch (action) {
    case 'copy':
      await copyService(service)
      break
    case 'stats':
      viewServiceDetail(service)
      break
    case 'reviews':
      // 查看客户评价
      viewServiceDetail(service)
      break
    case 'delete':
      await deleteService(service)
      break
  }
}

const copyService = async (service) => {
  try {
    const copyData = {
      ...service,
      name: `${service.name} (副本)`,
      id: undefined,
      createTime: undefined,
      updateTime: undefined
    }

    await createLaundryService(copyData)
    ElMessage.success('服务复制成功')
    refreshData()
  } catch (error) {
    ElMessage.error('服务复制失败')
    console.error('Copy service error:', error)
  }
}

const deleteService = async (service) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除服务 "${service.name}" 吗？删除后无法恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await deleteLaundryService(service.id)
    ElMessage.success('服务删除成功')
    refreshData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('服务删除失败')
      console.error('Delete service error:', error)
    }
  }
}

const batchUpdateStatus = async (status) => {
  try {
    const ids = selectedServices.value.map(s => s.id)
    await batchUpdateServiceStatus(ids, status)
    ElMessage.success('批量更新成功')
    selectedServices.value = []
    refreshData()
  } catch (error) {
    ElMessage.error('批量更新失败')
    console.error('Batch update error:', error)
  }
}

const batchDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedServices.value.length} 个服务吗？删除后无法恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const deletePromises = selectedServices.value.map(service => 
      deleteLaundryService(service.id)
    )
    await Promise.all(deletePromises)

    ElMessage.success('批量删除成功')
    selectedServices.value = []
    refreshData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除失败')
      console.error('Batch delete error:', error)
    }
  }
}

const handleFormSuccess = () => {
  refreshData()
}

// 生命周期
onMounted(() => {
  refreshData()
})
</script>

<style lang="scss" scoped>
.service-management {
  padding: 20px;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    .header-left {
      h1 {
        margin: 0 0 8px 0;
        font-size: 24px;
        font-weight: 600;
        color: #1f2937;
      }

      .description {
        margin: 0;
        color: #6b7280;
        font-size: 14px;
      }
    }

    .header-right {
      display: flex;
      gap: 12px;
    }
  }

  .service-stats {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 20px;
    margin-bottom: 30px;

    .stat-card {
      display: flex;
      align-items: center;
      padding: 20px;
      background: white;
      border-radius: 12px;
      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
      border: 1px solid #e5e7eb;

      .stat-icon {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 48px;
        height: 48px;
        border-radius: 12px;
        margin-right: 16px;

        &.active {
          background: linear-gradient(135deg, #10b981, #059669);
          color: white;
        }

        &.popular {
          background: linear-gradient(135deg, #f59e0b, #d97706);
          color: white;
        }

        &.revenue {
          background: linear-gradient(135deg, #8b5cf6, #7c3aed);
          color: white;
        }

        &.orders {
          background: linear-gradient(135deg, #3b82f6, #2563eb);
          color: white;
        }
      }

      .stat-content {
        h3 {
          margin: 0 0 4px 0;
          font-size: 24px;
          font-weight: 700;
          color: #1f2937;
        }

        p {
          margin: 0;
          font-size: 14px;
          color: #6b7280;
        }
      }
    }
  }

  .filter-section {
    padding: 20px;
    background: white;
    border-radius: 12px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    margin-bottom: 20px;
  }

  .service-list {
    background: white;
    border-radius: 12px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    overflow: hidden;

    .price-info {
      .price {
        font-weight: 600;
        color: #dc2626;
        font-size: 16px;
      }

      .unit {
        font-size: 12px;
        color: #6b7280;
      }
    }

    .sales-count {
      font-weight: 600;
      color: #059669;
    }

    .action-buttons {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
    }

    .pagination-wrapper {
      display: flex;
      justify-content: center;
      padding: 20px;
    }
  }

  .batch-actions {
    position: fixed;
    bottom: 20px;
    left: 50%;
    transform: translateX(-50%);
    z-index: 1000;

    .batch-content {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 16px 24px;

      .batch-buttons {
        display: flex;
        gap: 12px;
        margin-left: 20px;
      }
    }
  }
}
</style> 